﻿using log4net;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Usido.CRM.Core.Extensions;
using Usido.CRM.IRepository;
using Usido.CRM.Models;
using Usido.CRM.Repository;

namespace Usido.CRM.App.Forms
{
    public partial class 库存盘点管理 : Form
    {
        private readonly IStockProductBalanceRepository stockProductBalanceRepository = new StockProductBalanceRepository();
        private readonly ISysProductRepository productRepository = new SysProductRepository();
        private readonly ISysLogRepository logRepository = new SysLogRepository();
        private readonly IStockInventoryRepository stockInventoryRepository = new StockInventoryRepository();
        private readonly IStockInventoryDetailRepository stockInventoryDetailRepository = new StockInventoryDetailRepository();
        private readonly ILog logger = LogManager.GetLogger(nameof(药品销售管理));

        public 库存盘点管理()
        {
            InitializeComponent();
        }

        #region 窗体绘制

        /// <summary>
        /// 解决加载窗体多控件所造成的闪烁
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        #endregion 窗体绘制

        private string userId;
        private string userName;

        public 库存盘点管理(string userId, string userName)
        {
            InitializeComponent();
            this.userId = userId;
            this.userName = userName;
        }

        #region 取消按钮，默认退出

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion 取消按钮，默认退出

        #region 新增按钮，跳转页面。初始化 订单编号与订单状态

        /// <summary>
        /// 新增按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripAdd_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 1;

            lab_djbh.Text = "";
            lab_ddzt.Text = "制单";
            toolStripLabel2.Text = "";
            toolStripLabel3.Text = userName;
            Lab_HJcount.Text = "";
            toolStrip1.Text = "";
            toolStripLabel3.Text = "";
            toolStripLabel4.Text = "";
            txtProductName.Text = "";
            LAB_id.Text = "0";
            txtProductName.Select();
        }

        #endregion 新增按钮，跳转页面。初始化 订单编号与订单状态

        #region Load

        private void 采购入库管理_Load(object sender, EventArgs e)
        {
            dgvInventory.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            lab_djbh.Text = "";
            lab_ddzt.Text = "";
            toolStripLabel3.Text = userName;
            Lab_HJcount.Text = "";
            toolStrip1.Text = "";
            toolStripLabel3.Text = "";
            LAB_id.Text = "";
            txtProductName.Text = "";
            this.toolStripLabel4.Margin = new System.Windows.Forms.Padding(this.Width - 700, 1, 0, 2);
            BindData();
        }

        #endregion Load

        /// <summary>
        /// 绑定库存盘点单
        /// </summary>
        private void BindData()
        {
            dgvStockInventoryList.AutoGenerateColumns = false;
            var stockInventory = stockInventoryRepository.GetInventoryList().ToList();
            dgvStockInventoryList.Rows.Clear();
            for (int i = 0; i < stockInventory.Count; i++)
            {
                dgvStockInventoryList.Rows.Add();
                dgvStockInventoryList.Rows[i].Cells["订单编号"].Value = stockInventory[i].OrderCode;
                dgvStockInventoryList.Rows[i].Cells["制单人"].Value = stockInventory[i].UserName;
                dgvStockInventoryList.Rows[i].Cells["制单时间"].Value = stockInventory[i].CreateTime;
                dgvStockInventoryList.Rows[i].Cells["订单备注"].Value = stockInventory[i].Remark;
                dgvStockInventoryList.Rows[i].Cells["Id"].Value = stockInventory[i].Id;
                dgvStockInventoryList.Rows[i].Cells["订单状态"].Value = stockInventory[i].State == 0 ? "已保存" : "已完成";
                dgvStockInventoryList.Rows[i].DefaultCellStyle.BackColor = stockInventory[i].State == 0 ? Color.GreenYellow : Color.Gray;
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (lab_ddzt.Text.Contains("制单") || lab_ddzt.Text.Contains("已保存"))
            {
                try
                {
                    int index = dgvInventory.CurrentCell.RowIndex;
                    DialogResult RSS = MessageBox.Show(this, "确定要删除选中行数据码？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (RSS == DialogResult.Yes)
                    {
                        try
                        {
                            dgvInventory.Rows.RemoveAt(index);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("您还未选中有效行！");
                        }
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("您还未选中有效行！");
                }
            }
            else
            {
                MessageBox.Show("此订单状态无法修改!");
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (dgvInventory.Rows.Count <= 0)
            {
                MessageBox.Show("无数据可保存");
                return;
            }
            if (lab_ddzt.Text == "已完成")
            {
                MessageBox.Show("此订单已完成,无法修改!");
                return;
            }
            StockInventory inventory = new StockInventory();
            inventory.State = 0;
            inventory.Remark = txtRemark.Text.Trim();
            inventory.CreateTime = DateTime.Now;
            inventory.UserId = this.userId.ToInt();

            toolStripLabel4.Text = $"制表时间：{DateTime.Now }";

            List<StockInventoryDetail> list = new List<StockInventoryDetail>();
            for (int i = 0; i < dgvInventory.Rows.Count; i++)
            {
                StockInventoryDetail stockInventoryDetail = new StockInventoryDetail();
                stockInventoryDetail.ActualQuantity = dgvInventory.Rows[i].Cells["实盘数"].Value.ToString().ToDecimal();
                stockInventoryDetail.BatchNumber = dgvInventory.Rows[i].Cells["药品批号"].Value.ToString();
                if (dgvInventory.Rows[i].Cells["药品有效期"].Value != null && !dgvInventory.Rows[i].Cells["药品有效期"].Value.ToString().IsNullOrEmpty())
                {
                    stockInventoryDetail.DateExpiry = DateTime.Parse(dgvInventory.Rows[i].Cells["药品有效期"].Value.ToString());
                }
                stockInventoryDetail.InventorySurplusQuantity = dgvInventory.Rows[i].Cells["盘盈数量"].Value.ToString().ToDecimal();
                stockInventoryDetail.ProductId = dgvInventory.Rows[i].Cells["药品编码"].Value.ToString().ToInt();
                stockInventoryDetail.StockQuantity = dgvInventory.Rows[i].Cells["库存"].Value.ToString().ToDecimal();

                if (LAB_id.Text != "0")
                {
                    stockInventoryDetail.OrderId = LAB_id.Text.ToInt();
                }
                list.Add(stockInventoryDetail);
            }
            if (LAB_id.Text != "0")
            {

                inventory.Id = LAB_id.Text.ToInt();
                //修改
                var result = stockInventoryRepository.UpdateInventory(inventory, list);

                if (result)
                {
                    MessageBox.Show("修改成功");
                    BindData();
                    return;
                }
                else
                {
                    MessageBox.Show("修改失败，请稍后重试");
                    return;
                }
            }
            else
            {
                //新增
                int orderId = stockInventoryRepository.AddInventory(inventory, list);
                if (orderId > 0)
                {
                    LAB_id.Text = orderId.ToString();
                    lab_ddzt.Text = "已保存";
                    MessageBox.Show("保存成功");
                    BindData();
                    return;
                }
                else
                {
                    MessageBox.Show("保存失败，请稍后重试");
                    return;
                }
            }
        }
        /// <summary>
        /// 入库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (lab_ddzt.Text =="制单")
            {
                MessageBox.Show("请保存之后，再入库");
                return;
            }

            if (lab_ddzt.Text == "已完成" )
            {
                MessageBox.Show("该订单已完成，无法修改");
                return;
            }

            var orderId = LAB_id.Text.Trim().ToInt();
            var result = stockInventoryRepository.InStore(orderId, this.userId.ToInt());
            if (result)
            {
                lab_ddzt.Text = "已完成";
                MessageBox.Show("该订单已出库完成");
                return;
            }
            else
            {
                MessageBox.Show("该订单出库失败，请稍后重试");
                return;
            }
        }

        #region 绑定订单明细

        private void dgvSupplyList_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int index = dgvStockInventoryList.CurrentCell.RowIndex;
                string Id = dgvStockInventoryList.Rows[index].Cells["Id"].Value.ToString();
                lab_djbh.Text = dgvStockInventoryList.Rows[index].Cells["订单编号"].Value.ToString();
                lab_ddzt.Text = dgvStockInventoryList.Rows[index].Cells["订单状态"].Value.ToString();
                txtRemark.Text = dgvStockInventoryList.Rows[index].Cells["订单备注"].Value.ToString();
                LAB_id.Text = Id;
                var infoList = stockInventoryRepository.GetInventoryInfoList(Id.ToInt());
                tabControl1.SelectedIndex = 1;
                dgvInventory.Rows.Clear();
                for (int i = 0; i < infoList.Count; i++)
                {
                    dgvInventory.Rows.Add();
                    dgvInventory.Rows[i].Cells["药品编码"].Value = infoList[i].ProductId;
                    dgvInventory.Rows[i].Cells["药品名称"].Value = infoList[i].ProductName;
                    dgvInventory.Rows[i].Cells["规格"].Value = infoList[i].Specification;
                    dgvInventory.Rows[i].Cells["单位"].Value = infoList[i].MarketingUnit;
                    dgvInventory.Rows[i].Cells["库存"].Value = infoList[i].StockQuantity;
                    dgvInventory.Rows[i].Cells["实盘数"].Value = infoList[i].ActualQuantity;
                    dgvInventory.Rows[i].Cells["盘盈数量"].Value = infoList[i].InventorySurplusQuantity;
                    dgvInventory.Rows[i].Cells["生产企业"].Value = infoList[i].ManufacturingEnterprise;
                    dgvInventory.Rows[i].Cells["药品批号"].Value = infoList[i].BatchNumber;
                    dgvInventory.Rows[i].Cells["药品有效期"].Value = infoList[i].DateExpiry;
                }
                this.dgvInventory.Refresh();
            }
            catch (Exception w)
            {
            }
        }

        #endregion 绑定订单明细

        #region 解决切换卡顿重影

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int page = tabControl1.SelectedIndex;
            if (page == 0)
            {
                BindData();
            }
        }

        #endregion 解决切换卡顿重影

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                int index = dgvStockInventoryList.CurrentCell.RowIndex;
                //判断订单状态
                if (dgvStockInventoryList.Rows[index].Cells["订单状态"].Value.ToString() == "已完成")
                {
                    MessageBox.Show("该订单已完成，不能删除");
                    return;
                }
                var code = dgvStockInventoryList.Rows[index].Cells["订单编号"].Value.ToString();
                DialogResult RSS = MessageBox.Show(this, $"确定要删除库存盘点订单【{code}】？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (RSS == DialogResult.Yes)
                {
                    var id = dgvStockInventoryList.Rows[index].Cells["Id"].Value.ToString();

                    if (stockInventoryRepository.DeleteInventory(id.ToInt()))
                    {
                        string LogStr = $"删除{code}成功";
                        logRepository.AddLog(int.Parse(userId), LogStr);
                        MessageBox.Show(LogStr);
                        BindData();
                    }
                    else
                    {
                        MessageBox.Show("删除失败，请稍后重试");
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }

        private void txtProductName_TextChanged(object sender, EventArgs e)
        {
            string code = txtProductName.Text.Trim();
            var productList = stockProductBalanceRepository.GetStockInfoList(code);
            dgvProductList.AutoGenerateColumns = false;
            dgvProductList.DataSource = productList;
            dgvProductList.ClearSelection();
        }

        private void dgvProductList_KeyDown(object sender, KeyEventArgs e)
        {
            //回车
            if (e.KeyCode == Keys.Enter)
            {
                if (lab_ddzt.Text == "已完成")
                {
                    MessageBox.Show("此订单已完成,无法更改!");
                    return;
                }
                if (dgvProductList.SelectedRows.Count > 0)
                {
                    //实盘数量
                    string Count;

                    decimal shiPan = 0;

                    实盘数量 frmNum = new 实盘数量();
                    frmNum.ShowDialog();
                    if (frmNum.DialogResult.Equals(DialogResult.OK))
                    {
                        frmNum.Close();
                        Count = frmNum.Tag.ToString();
                        shiPan = decimal.Parse(Count);
                    }
                    else
                    {
                        return;
                    }
                    try
                    {
                        string Id = dgvProductList.SelectedRows[0].Cells["药品编号"].Value.ToString();
                        for (int i = 0; i < dgvInventory.Rows.Count; i++)
                        {
                            if (dgvInventory.Rows[i].Cells["药品编码"].Value.ToString() == Id)
                            {
                                MessageBox.Show("已存在该药品");
                                return;
                            }
                        }

                        var product = productRepository.Get(Id.ToInt());
                        string pihao = dgvProductList.SelectedRows[0].Cells["批号"].Value.ToString();
                        string guoqishijian = "";
                        if (dgvProductList.SelectedRows[0].Cells["过期时间"].Value != null)
                        {
                            guoqishijian = dgvProductList.SelectedRows[0].Cells["过期时间"].Value.ToString();
                        }
                        string kucun = dgvProductList.SelectedRows[0].Cells["dgv2库存"].Value.ToString();
                        decimal kuCunShu = decimal.Parse(kucun);
                        int index = dgvInventory.Rows.Add();
                        dgvInventory.Rows[index].Cells["药品编码"].Value = product.Id;
                        dgvInventory.Rows[index].Cells["药品名称"].Value = product.ProductName;
                        dgvInventory.Rows[index].Cells["规格"].Value = product.Specification;
                        dgvInventory.Rows[index].Cells["生产企业"].Value = product.ManufacturingEnterprise;
                        dgvInventory.Rows[index].Cells["库存"].Value = kucun;
                        dgvInventory.Rows[index].Cells["单位"].Value = product.MarketingUnit;
                        dgvInventory.Rows[index].Cells["药品批号"].Value = pihao;
                        dgvInventory.Rows[index].Cells["药品有效期"].Value = guoqishijian;
                        dgvInventory.Rows[index].Cells["实盘数"].Value = shiPan;
                        dgvInventory.Rows[index].Cells["盘盈数量"].Value = shiPan - kuCunShu;
                        dgvInventory.ClearSelection();
                        txtProductName.Focus();
                        txtProductName.Text = "";
                    }
                    catch (Exception E)
                    {
                    }
                }
            }
        }
    }
}